#include "musicinfo.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
void MainWindow::MusicInfo()
{
    //显示歌曲信息和图片
    ui->pic_display->show();
    ui->song_data->show();
    ui->song_data->viewport()->installEventFilter(this);
    QModelIndex currentIndex = ui->music_list->currentIndex();
    int currentRow = currentIndex.row(); // 获取行号
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui->music_list->model());
    QStandardItem *item =model->item(currentRow,0);//一开始是0
    //封面
    QIcon image =item->icon();
    //歌曲图片设置
    ui->pic_display->setIcon(image);
    ui->pic_display->setFixedSize(256, 256);
    ui->pic_display->move(ui->pic_display->x(),ui->pic_display->height()/3);
    ui->pic_display->setIconSize(QSize(250,250));
    ui->pic_display->setBackgroundRole(QPalette::Base);
    ui->pic_display->setStyleSheet(R"(
                            QPushButton {
                                border-radius: 10px;
                                border: none;
                                padding: 5px;
                                margin: 2px;
                            }
                        )");
    //图片展示显示阴影边框
    QGraphicsDropShadowEffect *shadowEffect_big = new QGraphicsDropShadowEffect;
    shadowEffect_big->setBlurRadius(30);        // 阴影模糊半径
    shadowEffect_big->setColor(QColor(0, 0, 0, 160)); // 阴影颜色和透明度
    shadowEffect_big->setOffset(6, 6);          // 阴影偏移量
    ui->pic_display->setGraphicsEffect(shadowEffect_big);
    QGraphicsDropShadowEffect *shadowEffect_little = new QGraphicsDropShadowEffect;
    shadowEffect_little->setBlurRadius(15);        // 阴影模糊半径
    shadowEffect_little->setColor(QColor(0, 0, 0, 160)); // 阴影颜色和透明度
    shadowEffect_little->setOffset(3, 3);          // 阴影偏移量
    ui->btn_lrc->setGraphicsEffect(shadowEffect_little);

    //歌词页面按钮(以当前播放歌曲为背景图片)
    ui->btn_lrc->setIcon(image);
    ui->btn_lrc->setFixedSize(80,80);
    ui->btn_lrc->setIconSize(QSize(ui->btn_lrc->width()-10, ui->btn_lrc->height()-10));
    ui->btn_lrc->setCursor(Qt::PointingHandCursor);
    ui->btn_lrc->setStyleSheet(R"(
                            QPushButton
                            {
                                border-radius: 10px;
                                border: none;
                            }
                            QPushButton:hover
                            {
                                background: rgba(0,0,0,50);/*悬停时背景颜色*/
                            }
                        )");
    //右下角歌曲名称显示
    ui->song_name->setText(item->data(Qt::UserRole).toString());
    ui->song_name->setFixedWidth(300);//标题和歌词显示的最大长度
    ui->song_name->adjustSize();
    ui->song_name->move(ui->btn_lrc->x()-ui->song_name->width(),ui->btn_lrc->y()+10);
    //歌词显示(右下角)
    ui->song_lrc->setText(ui->song_name->text());
    ui->song_lrc->setFixedWidth(ui->song_name->width());
    ui->song_lrc->move(ui->song_name->x(),ui->song_name->y()+ui->song_name->height());

    //歌曲信息设置
    ui->song_data->setFixedSize(256, ui->lyric_display->height()-256);
    //ui->song_data->setFixedWidth(256);
    ui->song_data->move(ui->pic_display->x(),ui->pic_display->y()+ui->pic_display->height()+5);
    ui->song_data->setStyleSheet("QListWidget "
                                 "{ "
                                 "background-color: transparent;"
                                 "}");
    SongData(ui,play_song_list);
}

void SongData(Ui::MainWindow *ui,QTableView *tableview)
{
    ui->song_data->clear();
    QModelIndex currentIndex = tableview->currentIndex();
    int currentRow = currentIndex.row(); // 获取行号
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *item =model->item(currentRow,0);//一开始是0
    QStringList items;
    items <<"标题："+item->data(Qt::UserRole+0).toString()
          <<"艺术家："+ item->data(Qt::UserRole+1).toString()
          <<"专辑："+ item->data(Qt::UserRole+2).toString();
    ui->song_data->addItems(items);
    //左对齐
    for (int i = 0; i < ui->song_data->count(); i++) {
        QListWidgetItem *item = ui->song_data->item(i);
        item->setTextAlignment(Qt::AlignLeft);
    }
    //启用换行
    ui->song_data->setWordWrap(true);
}




//获取歌曲信息
MainWindow::MusicMetaData getMusicData(const QString filePath,bool isAllInfo)
{
    MainWindow::MusicMetaData metaData;

    QMediaPlayer player;
    player.setSource(QUrl::fromLocalFile(filePath));
    QEventLoop loop;
    QObject::connect(&player, &QMediaPlayer::mediaStatusChanged, [&](QMediaPlayer::MediaStatus status) {
        qDebug() << "媒体状态变化:" << status;
        if (status == QMediaPlayer::LoadedMedia ) {
            loop.quit();
        }

    });
    loop.exec();
    // 获取封面数据
    QVariant coverData = player.metaData().value(QMediaMetaData::ThumbnailImage);
    //获取歌曲封面
    metaData.image=coverData.value<QImage>();
    metaData.duration =player.metaData().stringValue(QMediaMetaData::Duration)+ "秒";
    //获取其他数据
    QProcess process;
    QStringList arguments;
    arguments << "-v" << "quiet"
              << "-print_format" << "json"
              << "-show_format"
              << "-show_streams"
              << filePath;

    process.start("ffprobe", arguments);
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString jsonStr=QString::fromUtf8(output);

    QJsonDocument doc = QJsonDocument::fromJson(jsonStr.toUtf8());
    QJsonObject root = doc.object();

    // 解析格式信息
    if (root.contains("format")) {
        QJsonObject format = root["format"].toObject();
        // qDebug() << "格式名称:" << format["format_name"].toString();
        // qDebug() << "格式长名称:" << format["format_long_name"].toString();
        //qDebug() << "时长:" << format["duration"].toString() << "秒";
        // qDebug() << "大小:" << format["size"].toString() << "字节";
        // qDebug() << "比特率:" << format["bit_rate"].toString() << "bps";
        //metaData.duration=(format["duration"].toInt()/1000).t;
        // 标签信息
        if (format.contains("tags")) {
            QJsonObject tags = format["tags"].toObject();


            metaData.title = tags["title"].toString();
            metaData.author = tags["artist"].toString();
            metaData.albumTitle = tags["album"].toString();
            //metaData.genre = tags["genre"].toString();

            // qDebug() << "标题:" << tags["title"].toString();
            // qDebug() << "艺术家:" << tags["artist"].toString();
            // qDebug() << "专辑:" << tags["album"].toString();
            // qDebug() << "年份:" << tags["date"].toString();
            //qDebug() << "流派:" << tags["genre"].toString();
        }
    }
    //是否获取全部信息
    if(isAllInfo)
        if (root.contains("streams")) {
            QJsonArray streams = root["streams"].toArray();
            for (const QJsonValue &streamValue : streams) {
                QJsonObject stream = streamValue.toObject();
                QString codecType = stream["codec_type"].toString();
                if (codecType == "audio") {
                    // qDebug() << "音频流:";
                    // qDebug() << "  编码器:" << stream["codec_name"].toString();
                    // qDebug() << "  采样率:" << stream["sample_rate"].toString() << "Hz";
                    // qDebug() << "  声道数:" << stream["channels"].toString();
                    // qDebug() << "  声道布局:" << stream["channel_layout"].toString();
                    // qDebug() << "  比特率:" << stream["bit_rate"].toString() << "bps";
                    metaData.codec_name= stream["codec_name"].toString();
                    metaData.sample_rate= stream["sample_rate"].toString() +"Hz";
                    metaData.bit_rate=stream["bit_rate"].toString()+"bps";
                }
                else if (codecType == "video") {

                    // qDebug() << "  分辨率:" << stream["width"].toString()
                    //          << "x" << stream["height"].toString();
                    // qDebug() << "  帧率:" << stream["r_frame_rate"].toString();
                    // qDebug() << "  像素格式:" << stream["pix_fmt"].toString();
                }
            }
        }
    //qDebug()<<"++++++++++++++++++++";
    return  metaData;
}
